package util

import (
	"fmt"
	"github.com/casbin/casbin/v2"
	gormadapter "github.com/casbin/gorm-adapter/v2"
	"github.com/spf13/viper"
)

func Casbin() (*casbin.Enforcer, error) {
	dns := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true&loc=Local",
		viper.GetString("storage.user"),
		viper.GetString("storage.password"),
		viper.GetString("storage.host"),
		viper.GetString("storage.port"),
		viper.GetString("storage.dbname"),
		viper.GetString("storage.charset"),
	)
	// 适配器
	adapter, err := gormadapter.NewAdapter(viper.GetString("storage.driver"), dns, true)
	if err != nil {
		return nil, err
	}
	//
	e, err := casbin.NewEnforcer("./config/rbac_model.conf", adapter)
	if err != nil {
		return nil, err
	}
	// 加载策略从数据库
	if err = e.LoadPolicy(); err != nil {
		return nil, err
	} else {
		return e, err
	}
}
